package main

import (
	"archive/zip"
	"bufio"
	"fmt"
	"io"
	"math"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/tealeg/xlsx"
)

// SaveFile 保存上传的文件
func (a *App) SaveFile(filename string, data []interface{}) error {
	fmt.Println("filename:", filename)
	fmt.Println("data:", data)
	return nil
}
func (a *App) FileHandler(table, filePath, name string, fieldInfo []map[string]interface{}, start int) map[string]interface{} {
	var dataMap = make(map[string]interface{})
	xlFile, err := xlsx.OpenFile(filePath)
	INSERT_err := ""
	if err != nil {
		fmt.Printf("打开文件出错：%v", err)
	}
	values := ""
	field := ""
	datadb := datadbMap[name]
	var nums int64 = 0
	for t := 0; t < len(fieldInfo); t++ {
		if field == "" {
			field = "`" + fieldInfo[t]["Field"].(string) + "`"
		} else {
			field = field + ",`" + fieldInfo[t]["Field"].(string) + "`"
		}
	}
	for i := 0; i < len(xlFile.Sheets); i++ {
		sheet := xlFile.Sheets[i]
		values = ""
		for n := 0; n < len(sheet.Rows); n++ {
			row := sheet.Rows[n]
			if n >= start-1 {
				value := ""
				for t := 0; t < len(fieldInfo); t++ {
					Column := int(math.Floor(fieldInfo[t]["Column"].(float64) - 1))
					fmt.Println("99:", row.Cells[Column].Type(), row.Cells[Column])
					Cells := row.Cells[Column].String()
					if fieldInfo[t]["relateTable"] != nil {
						Cells = "(SELECT " + fieldInfo[t]["relateKey"].(string) + " FROM " + fieldInfo[t]["relateTable"].(string) + " WHERE `" + fieldInfo[t]["relateValue"].(string) + "` = '" + row.Cells[Column].String() + "')"
					}
					if value == "" {
						if fieldInfo[t]["Type"].(string) == "int" || fieldInfo[t]["relateTable"] != nil {
							value = Cells
						} else {
							value = "'" + Cells + "'"
						}
					} else {
						if fieldInfo[t]["Type"].(string) == "int" || fieldInfo[t]["relateTable"] != nil {
							value = value + "," + Cells
						} else {
							value = value + ",'" + Cells + "'"
						}
					}
				}
				if values == "" {
					values = "(" + value + ")"
				} else {
					values = values + ",(" + value + ")"
				}

				if (n-start)%100 == 0 {
					res, err := datadb.Raw("INSERT INTO " + table + "(" + field + ") VALUES " + values).Exec()
					if err == nil {
						num, _ := res.RowsAffected()
						nums += num
						fmt.Println("mysql row affected nums: ", num)
					} else {
						INSERT_err = INSERT_err + err.Error()
					}
					values = ""
				}
			}
		}
		fmt.Println("INSERT INTO " + table + "(" + field + ") VALUES " + values)
		if values != "" {
			res, err := datadb.Raw("INSERT INTO " + table + "(" + field + ") VALUES " + values).Exec()
			if err == nil {
				num, _ := res.RowsAffected()
				nums += num
				fmt.Println("mysql row affected nums: ", num)
			} else {
				INSERT_err = INSERT_err + err.Error()
			}
			values = ""
		}
	}
	if values != "" {
		res, err := datadb.Raw("INSERT INTO " + table + "(" + field + ") VALUES " + values).Exec()
		if err == nil {
			num, _ := res.RowsAffected()
			nums += num
			fmt.Println("mysql row affected nums: ", num)
		} else {
			INSERT_err = INSERT_err + err.Error()
		}
	}
	if INSERT_err != "" {
		dataMap["code"] = 500
		dataMap["msg"] = INSERT_err
		dataMap["data"] = "插入总条数：" + strconv.FormatInt(nums, 10)
	} else {
		dataMap["code"] = 200
		dataMap["msg"] = ""
		dataMap["data"] = "插入总条数：" + strconv.FormatInt(nums, 10)
	}
	return dataMap
}

func (a *App) FileHandler2(filePath string) interface{} {
	if strings.Contains(filePath, ".xlsx") {
		filePath = strings.Split(filePath, ".")[0]
	}
	copyFile(filePath+".xlsx", filePath+"_mfp.xlsx")
	os.Rename(filePath+"_mfp.xlsx", filePath+"_mfp.zip")
	Unzip(filePath+"_mfp.zip", filePath+"_mfp")
	os.Remove(filePath + "_mfp.zip")
	relsimgMap := relsCellimages(filePath)
	imgMap := Cellimages(filePath)
	imageMap = make(map[string]interface{})
	for k, v := range relsimgMap {
		v = strings.ReplaceAll(v.(string), "\"", "")
		imgMap[k] = strings.ReplaceAll(imgMap[k].(string), "\"", "")
		imageMap[v.(string)] = imgMap[k]
	}
	fmt.Println(imageMap)
	// os.RemoveAll(filePath + "_mfp")
	return nil
}

// 读取rels/Cellimages.xml文件
func relsCellimages(filePath string) map[string]interface{} {
	xmlFile, err := os.Open(filePath + "_mfp\\xl\\cellimages.xml")
	if err != nil {
		fmt.Printf("Error opening file: %v", err)
	}
	scanner := bufio.NewScanner(xmlFile)
	var imgList []string
	for scanner.Scan() {
		line := scanner.Text()
		if strings.Contains(line, "etc:cellImages") {
			x := ""
			for i := 0; i < len(line); i++ {
				if line[i] == '<' || line[i] == '/' {
					continue
				}
				if line[i] == '>' {
					xs := strings.Split(x, " ")
					if xs[0] == "xdr:cNvPr" {
						cNvPr := strings.Split(xs[2], "=")[1]
						imgList = append(imgList, cNvPr)
					}
					if xs[0] == "a:blip" {
						embed := strings.Split(xs[1], "=")[1]
						imgList = append(imgList, embed)
					}
					x = ""
				} else {
					x = x + string(line[i])
				}
			}
		}
	}
	imgs := len(imgList) / 2
	relsimgMap := make(map[string]interface{})
	for i := 0; i < imgs; i++ {
		relsimgMap[imgList[i*2+1]] = imgList[i*2]
	}
	xmlFile.Close()
	return relsimgMap
}

// 读取/Cellimages.xml文件
func Cellimages(filePath string) map[string]interface{} {
	xmlFile, err := os.Open(filePath + "_mfp\\xl\\_rels\\cellimages.xml.rels")
	if err != nil {
		fmt.Printf("Error opening file: %v", err)
	}
	scanner := bufio.NewScanner(xmlFile)
	var imgList []string
	for scanner.Scan() {
		line := scanner.Text()
		if strings.Contains(line, "Relationships") {
			x := ""
			for i := 0; i < len(line); i++ {
				if line[i] == '<' || line[i] == '/' {
					continue
				}
				if line[i] == '>' {
					xs := strings.Split(x, " ")
					if xs[0] == "Relationship" {
						Id := strings.Split(xs[1], "=")[1]
						Target := strings.Split(xs[3], "=")[1]
						imgList = append(imgList, Id)
						imgList = append(imgList, Target)
					}
					x = ""
				} else {
					x = x + string(line[i])
				}
			}
		}
	}
	imgs := len(imgList) / 2
	imgMap := make(map[string]interface{})
	for i := 0; i < imgs; i++ {
		imgMap[imgList[i*2]] = imgList[i*2+1]
	}
	xmlFile.Close()
	return imgMap
}

// copyFile 函数用于将文件从源路径复制到目标路径
func copyFile(src, dst string) error {
	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	dstFile, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer dstFile.Close()

	_, err = io.Copy(dstFile, srcFile)
	return err
}

// Unzip 函数用于解压缩 zip 文件
func Unzip(src string, dest string) error {
	r, err := zip.OpenReader(src)
	if err != nil {
		return err
	}
	defer r.Close()

	for _, f := range r.File {
		// 检查文件是否是文件夹
		if f.FileInfo().IsDir() {
			os.MkdirAll(filepath.Join(dest, f.Name), f.Mode())
		} else {
			// 创建目标文件
			rc, err := f.Open()
			if err != nil {
				return err
			}
			defer rc.Close()

			path := filepath.Join(dest, f.Name)
			// 创建文件所在的目录
			if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
				return err
			}
			w, err := os.Create(path)
			if err != nil {
				return err
			}
			defer w.Close()
			// 将文件内容从压缩文件复制到目标文件
			_, err = io.Copy(w, rc)
			if err != nil {
				return err
			}
		}
	}
	return nil
}
